import router from '@/router/index.js'

export default {
  namespaced: true,
  state: {
    user: {},
    token: '',
    ticket: ''
  },
  getters: {
    getToken: state => {
      state.token = localStorage.getItem("token")
      return state.token || ''
    },
    getTicket: state => {
      state.ticket = localStorage.getItem("ticket")
      return state.ticket || ''
    },
    getUser: state => {
      return state.user
    },
  },
  mutations: {
    setUser (state, data) {
      state.user = data
    },
    removeToken: (state) => {
      state.token = '';
      localStorage.removeItem('token')
    },
    setToken: (state, token) => {
      state.token = token
      localStorage.setItem("token", token)
    },
    removeTicket: (state) => {
      state.ticket = '';
      localStorage.removeItem('ticket')
    },
    setTicket: (state, ticket) => {
      state.ticket = ticket
      localStorage.setItem("ticket", ticket)
    },
    generateRoutes: (state) => {
      const { menus } = state.user;
      routerChildren(menus)
      // console.log(menus);
      menus.forEach(r => {
        router.addRoute('home', r)
      })
      // console.log(router.getRoutes())
    }
  }

}

function routerCom (path) { // 对路由的component解析
  // 这里路径需要后台给
  return (resolve) => require([`@/components/${path}.vue`], resolve)
}

function routerChildren (children) {
  children.forEach(v => {
    if (v.component) {
      v.component = routerCom(v.component)
    } else {
      v.component = { render: (e) => e("router-view") }
    }
    v.path = v.url
    // === '#' ? '/' + v.name : v.url
    if (v.children?.length) {
      routerChildren(v.children)
    }
  })
}
